package com.shg.service.impl;

import java.math.BigInteger;
import java.util.LinkedHashMap;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Service;

import com.shg.bean.Book;
import com.shg.bean.BookType;
import com.shg.bean.BuyItem;
import com.shg.bean.Online;
import com.shg.bean.PageView;
import com.shg.bean.QueryResult;
import com.shg.bean.Shop;
import com.shg.bean.TypeSearch;
import com.shg.service.BookService;

@Service
public class BookServiceBean extends BasiceDaoImpl<Book> implements BookService{

	/**
	 * 组成下面的SQL语句
	 * from book where id in('4028896135a2e4450135a2eaee660000','ff80808135a045270135a0452a5c0000')
	 * 
	 */
	@SuppressWarnings("unchecked")
	public List<Book> getHistory(Class<Book> entity,String [] idList)throws Exception {
		if(idList!=null){
			String sql="from "+entity.getSimpleName()+" where id in (";
			for(int i=0;i<idList.length;i++){
				sql+="'"+idList[i]+"',";
			}
			sql = sql.substring(0, sql.lastIndexOf(",")) + ")";
			sql+=" and shows=1";
			Query query = sessionFactory.getCurrentSession().createQuery(sql);
			return query.list();
		}else{
			return null;
		}
	}
	/**
	 * 分类查询某个店铺的书籍列表
	 * 注意查询的条件是：1、shop_id是当前这个店铺的ID 2、店铺的shop_id为null（表示的是父类）
	 *  from book where shop_id is null or shop_id='ff80808135a033220135a033246c0000'
	 */
	@SuppressWarnings("unchecked")
	public List<Book> getForType(Class<Book> entity,String shopID){
		String sql="from "+entity.getSimpleName()+" where shop_id is null or shop_id='"+shopID+"'";
		Query query = sessionFactory.getCurrentSession().createQuery(sql);
		List<Book> list = query.list();
		return list;
	}
	/**
	 * 根据传递进来的ID查询某本书籍，
	 * 如果查询出来书籍的话，在根据得到的ID来查询
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Book getBook(String id){
		Book book = (Book)sessionFactory.getCurrentSession().get(Book.class, id);
		//获取店铺的ID
		if(book!=null){
			String shop_id = book.getShop().getId();
			Shop shop = (Shop) sessionFactory.getCurrentSession().get(Shop.class, shop_id);
			book.setShop(shop);
			Query query = sessionFactory.getCurrentSession().createQuery("from Online where shop_id=? and service=1");
			List<Online> onlines = query.setParameter(0, shop_id).list();
			for(Online online:onlines){
				shop.getOnlines().add(online);
			}
			BookType bookType = (BookType) sessionFactory.getCurrentSession().get(BookType.class, book.getParent().getId());
			book.setParent(bookType);
		}
		return book;
	}
	
	/**
	 * 店铺精品（推荐的书籍）
	 * @param entity查询的实体对象
	 * @param firstResult 查询的起始位置
	 * @param maxResult 需要查询的记录数
	 */
	public QueryResult<Book> getRecommend(String shopid,int firstResult,int maxResult){
		String whereSQL="recommend = ? and shows=? and shop_id='"+shopid+"'";
		Object [] parameters=new Object[]{1,1};
		LinkedHashMap<String, String> orderBy=new LinkedHashMap<String, String>();
		orderBy.put("dateLine", "desc");
		QueryResult<Book> result = getPagination(Book.class, firstResult, maxResult, whereSQL, parameters, orderBy);
		return result;
	}
	/**
	 * 查询所有店铺推荐出去的书籍
	 * @param pageView 分页视图
	 * @throws Exception 
	 */
	public QueryResult<Book> getRecommend(PageView<Book> pageView) throws Exception{
		String whereSQL=" where recommend = 1 and shows=1 ";
		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("love", "desc");
		return getBasicBook(pageView,whereSQL,orderby);
	}
	/**
	 *获取店铺推荐的书籍
	 *排序方式，实现按店铺查询排序出来
	 *		然后按love
	 *		最后安装recommend
	 *@param pageView 分页组件
	 */
	public QueryResult<Book> getShopRecommend(PageView<Book> pageView)throws Exception{
		String whereSQL=" where  shows=1 ";
		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("shop", "desc");
		orderby.put("love", "desc");
		orderby.put("recommend", "desc");
		return getBasicBook(pageView,whereSQL,orderby);
	}
	/**
	 * 该方法为分页查询Book方法，功能特别之处在于能深入查询
	 * 入书籍管理的店铺，开店人，服务人员等等
	 * @param pageView
	 * @param orderby
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private QueryResult<Book> getBasicBook(PageView<Book> pageView,String whereSQL,LinkedHashMap<String, String> orderby)throws Exception{
		String where =  (whereSQL==null ||"".equals(whereSQL.trim()))?"":whereSQL;
		String sql="from Book "+where+buildSQL(orderby);
		QueryResult<Book> result = new QueryResult<Book>();
		List<Book> books = sessionFactory.getCurrentSession().createQuery(sql)
										.setFirstResult(pageView.getFirstResult())
										.setMaxResults(pageView.getMaxrecord())
										.list();
		for(Book book:books){
			Shop shop=(Shop) sessionFactory.getCurrentSession().get(Shop.class, book.getShop().getId());
			book.setShop(shop);
			BookType bookType=(BookType) sessionFactory.getCurrentSession().get(BookType.class, book.getParent().getId());
			book.setParent(bookType);
		}
		result.setResultList(books);
		//总记录
		whereSQL="select count(*) from Book "+where;
		BigInteger count=(BigInteger) sessionFactory.getCurrentSession().createSQLQuery(whereSQL).list().get(0);
		result.setResultCount(count.longValue());
		return result;
	}
	/**
	 * 查询新书热卖，1、按时间排序 2、热卖
	 * @param shopid 店铺ID
	 * @param firstResult 查询的起始位置
	 * @param maxResult 每页返回的最大的记录数
	 * @return
	 */
	public QueryResult<Book> getNewBook(String shopid,int firstResult,int maxResult)throws Exception{
		String whereSQL=null;
		if(shopid==null){
			whereSQL=" shows=?";
		}else{
			whereSQL=" shows=? and shop_id='"+shopid+"'";
		}
		Object [] parameters=new Object[]{1};
		LinkedHashMap<String, String> orderBy=new LinkedHashMap<String, String>();
		orderBy.put("dateLine", "desc");
		QueryResult<Book> result = getPagination(Book.class, firstResult, maxResult, whereSQL, parameters, orderBy);
		return result;
	}
	/**
	 * 查询新书热卖，1、按时间排序 2、热卖
	 * @param firstResult 查询的起始位置
	 * @param maxResult 每页返回的最大的记录数
	 * @return
	 */
	public QueryResult<Book> getAuditingBook(int firstResult,int maxResult)throws Exception{
		LinkedHashMap<String, String> orderBy=new LinkedHashMap<String, String>();
		orderBy.put("dateLine", "desc");
		QueryResult<Book> result = getPagination(Book.class, firstResult, maxResult, orderBy);
		return result;
	}
	/**
	 * 更新书籍的推荐状态
	 * @param bookid 书籍的ID列表
	 * @param state书籍的状态 1、推荐 0、取消推荐
	 */
	public void updateRecommend(String[] bookid,int state){
		String sql="update Book set recommend="+state+" where id in(";
		for(String id:bookid){
			sql+="'"+id+"',";
		}
		sql = sql.substring(0, sql.lastIndexOf(","));
		sql+=")";
		sessionFactory.getCurrentSession().createQuery(sql).executeUpdate();
	}
	/**
	 * 书籍的上、下架
	 * @param bookid书籍的ID数组
	 * @param state状态1.上架、2.待审核，3.问题书籍，4、售出书籍
	 */
	public void updateShow(String[] bookid,int state){
		String sql="update Book set shows="+state+" where id in(";
		for(String id:bookid){
			sql+="'"+id+"',";
		}
		sql = sql.substring(0, sql.lastIndexOf(","));
		sql+=")";
		sessionFactory.getCurrentSession().createQuery(sql).executeUpdate();
	}
	/**
	 * 查询购物车书籍
	 */
	@SuppressWarnings("unchecked")
	public List<Book> getCatBook(List<BuyItem> list){
		String sql="from Book where id in(";
		for(BuyItem item:list){
			sql+="'"+item.getId()+"',";
		}
		sql=sql.substring(0, sql.lastIndexOf(","));
		sql+=")";
		List<Book> books = sessionFactory.getCurrentSession().createQuery(sql).list();
		return books;
	}
	/**
	 * 获取最受欢迎的书籍
	 */
	public QueryResult<Book> getLove(String shopId,PageView<Book> pageView)throws Exception{
		//查询书籍 如果shopId为null是统计这个网站的销售的书籍  否则为统计整个店铺的销售书籍
		String whereSQL=null;
		Object[]parameters=null;
		if(shopId==null || shopId.equals("")){
			whereSQL=" shows=? ";
			parameters = new Object[]{1};
		}else{
			whereSQL=" shows=? and shop_id=?";
			parameters = new Object[]{1,"'"+shopId+"'"};
		}
		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("love", "desc");
		QueryResult<Book> result = getPagination(Book.class, pageView.getFirstResult(), pageView.getMaxrecord(), whereSQL, parameters, orderby);
		return result;
	}
	/**
	 * 根据ID查询所有的书籍
	 */
	public List<Book> getByIds(String[] ids) {
		String sql="from Book where shows=1 and id in(";
		for(String id : ids){
			sql+="'"+id+"',";
		}
		int index = sql.lastIndexOf(",");
		if(index!=-1){
			sql = sql.substring(0, index);//from Book where id in('xxx','xxx'
		}else{
			sql+="null";//from Book where id in(null
		}
		sql+=")";
		List<Book> result = sessionFactory.getCurrentSession().createQuery(sql).list();
		for(Book book:result){
			Shop shop=(Shop) sessionFactory.getCurrentSession().get(Shop.class, book.getShop().getId());
			book.setShop(shop);
		}
		return result;
	}
	/**
	 * 分页查询指定类别下的书籍
	 * @param pageView 分页工具栏
	 * @param ids id
	 * 			格式：'xxxxx','xxxx','xxxx'
	 *  
	 */
	@SuppressWarnings("unchecked")
	public QueryResult<Book> getTypeList(PageView<Book> pageView,String id)throws Exception{
		QueryResult<Book> result=new QueryResult<Book>();
		TypeSearch typeSearch=(TypeSearch) sessionFactory.getCurrentSession().get(TypeSearch.class, id);
		
		String sql="from Book where parent in("+typeSearch.getChild()+") order by id desc";
		List<Book> list = sessionFactory.getCurrentSession().createQuery(sql)
								.setFirstResult(pageView.getFirstResult())
								.setMaxResults(pageView.getMaxrecord()).list();
		result.setResultList(list);
		//总记录
		sql="select count(*)  from Book where parent_id in("+typeSearch.getChild()+")";
		BigInteger count = (BigInteger) sessionFactory.getCurrentSession().createSQLQuery(sql).list().get(0);
		result.setResultCount(count.longValue());
		return result;
	}
	/**
	 * 查询店铺的书籍
	 */
	public QueryResult<Book> getShopTypeList(PageView<Book> view ,String shopid, String typeId)
			throws Exception {
		QueryResult<Book> result=new QueryResult<Book>();
		TypeSearch typeSearch=(TypeSearch) sessionFactory.getCurrentSession().get(TypeSearch.class, typeId);
		
		String sql="from Book where shop_id='"+shopid+"' and parent in("+typeSearch.getChild()+") order by id desc";
		List<Book> list = sessionFactory.getCurrentSession().createQuery(sql)
								.setFirstResult(view.getFirstResult())
								.setMaxResults(view.getMaxrecord()).list();
		result.setResultList(list);
		//总记录
		sql="select count(*)  from Book where parent_id in("+typeSearch.getChild()+")";
		BigInteger count = (BigInteger) sessionFactory.getCurrentSession().createSQLQuery(sql).list().get(0);
		result.setResultCount(count.longValue());
		return result;
	}
	
	/**
	 * 猜你都喜欢的
	 * 
	 */
	@SuppressWarnings("unchecked")
	public QueryResult<Book> getYouLove(String typeId,PageView<Book> pageView)throws Exception{
		QueryResult<Book> result=new QueryResult<Book>();
		String sql="from Book where shows=1 and parent='"+typeId+"'";
		List<Book> list=sessionFactory.getCurrentSession().createQuery(sql)
						.setFirstResult(pageView.getFirstResult())
						.setMaxResults(pageView.getMaxrecord())
						.list();
		result.setResultList(list);
		
		sql="select count(*) from Book where shows=1 and parent_id='"+typeId+"'";
		BigInteger count = (BigInteger) sessionFactory.getCurrentSession().createSQLQuery(sql).list().get(0);
		result.setResultCount(count.longValue());
		return result;
	}
	/**
	 * 顶一下自己喜欢的书籍，该书籍有机会排名向前，可能出现在首页
	 */
	public void updateLove(String bookid) throws Exception {
		String sql="update Book set love=love+1 where id='"+bookid+"'";
		sessionFactory.getCurrentSession().createSQLQuery(sql).executeUpdate();
	}
	/**
	 * 将这本书籍设置为禁书
	 */
	public void updateAuditing(Book book) throws Exception {
		String sql="update book set shows="+book.getShow()+" , remark='"+book.getRemark()+"' where id='"+book.getId()+"'";
		sessionFactory.getCurrentSession().createSQLQuery(sql).executeUpdate();
	}
}
